package com.fable.ntzw_ga.controller;


import cn.hutool.core.convert.Convert;
import com.fable.common.eunm.AppHttpCodeEnum;
import com.fable.common.utils.IpUtil;
import com.fable.common.utils.RandomValidateCodeUtil;
import com.fable.common.utils.RedisUtil;
import com.fable.common.vo.ResultVO;
import com.fable.ntzw_ga.entity.SysUser;
import com.fable.ntzw_ga.service.ISysUserService;
import io.jsonwebtoken.Jwts;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Created by gzh 2023-02-19 23:49:21
 */
@Api(tags = "管理员")
@RestController
@RequestMapping("/ntzw_ga/sys-user")
@Slf4j
public class SysUserController {

    @Autowired
    ISysUserService sysUserService;

    @Autowired
    RandomValidateCodeUtil randomValidateCodeUtil;

    @Autowired
    RedisUtil redisUtil;

    @Value("${jwt.secret}")
    private String secret;

    @ApiOperation(value = "登录之后返回token")
    @PostMapping("/login")
    public ResultVO login(@RequestBody SysUser sysUser) {
        return sysUserService.login(sysUser);
    }

    @ApiOperation(value = "token返回获取名字")
    @PostMapping("/reUserName")
    public ResultVO reUserName(@RequestBody String token) {
        String getUsername = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody().getSubject();
        return ResultVO.okResult(getUsername);
    }

    @ApiOperation(value = "注册")
    @PostMapping("/signUp")
    public ResultVO signUp(@RequestBody SysUser sysUser) {
        // 加密
        sysUser.setPassword(BCrypt.hashpw(sysUser.getPassword(), BCrypt.gensalt())) ;
        return ResultVO.okResult(sysUserService.save(sysUser));
    }

    /**
     * @description 生成验证码
     */
    @ApiOperation(value = "生成验证码")
    @GetMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        try {
            //设置相应类型,告诉浏览器输出的内容为图片
            response.setContentType("image/jpeg");
            //设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            //输出验证码图片方法
            randomValidateCodeUtil.getRandcode(request, response);
        } catch (Exception e) {
            log.error("获取验证码失败>>>>", e);
        }
    }

    /**
     * @description 校验验证码
     */
    @ApiOperation(value = "校验验证码")
    @PostMapping("/checkVerify")
    public ResultVO checkVerify(@RequestBody String verifyInput, HttpServletRequest request) {
        try {
            String ip = IpUtil.getIpAddress(request);
            if (redisUtil.isExpire(ip)) {
                return ResultVO.errorResult(AppHttpCodeEnum.CAPTCHPA_EXPIRE);
            }else {
                String random = Convert.toStr(redisUtil.get(ip));
                // 比较字符串，不区分大小写
                if (random.equalsIgnoreCase(verifyInput)) {
                    return ResultVO.okResult(AppHttpCodeEnum.SUCCESS);
                } else {
                    return ResultVO.errorResult(AppHttpCodeEnum.CAPTCHPA_ERROE);
                }
            }
        } catch (Exception e) {
            log.error("验证码校验失败", e);
            return ResultVO.errorResult(AppHttpCodeEnum.ERROR);
        }
    }

}
